package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 处理登录认证功能
 */
//@WebFilter("/*")  //配置过滤器的拦截路径   /*表示拦截所有
@Slf4j
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //1. 将ServletRequest类型转换为HttpServletRequest类型
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        //2. 判断该请求路径是否是登录功能 /login
        if (req.getRequestURI().contains("/login")) {
            //放行
            chain.doFilter(request, response);
            //必须加return，结束
            return;
        }
        //3. 获取令牌，token请求头
        String token = req.getHeader("token");
        //4. 解析校验token
        try {
            JwtUtils.parseJWT(token);
            //放行
            chain.doFilter(request, response);
            return;
        } catch (Exception e) {
            //说明用户未登录，或者token异常
            Result not_login = Result.error("NOT_LOGIN");
            //将Result对象转为json字符串
            String json = JSON.toJSONString(not_login);
            resp.getWriter().write(json);
            log.info("用户未登录 {}", json);
        }
    }
}
